package kr.hkit.wordnote.fragment;

import com.example.wordnote2.R;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class WordFindFragment extends Fragment {
	WebView web;
	final static String TAG = "WordFindFragment";
	
	public static WordFindFragment newInstance(){
		WordFindFragment frag = new WordFindFragment();
		return frag;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LinearLayout linear = (LinearLayout)inflater.inflate(R.layout.wordfindfragment, container, false);
		
		Button btnFind = (Button)linear.findViewById(R.id.btn_find);
		btnFind.setOnClickListener(mClick);
		//웹뷰를 사용하기 위한 객체를 만든다. 
		web = (WebView)linear.findViewById(R.id.web);
		web.setWebViewClient(new MyWebClient());
		WebSettings set = web.getSettings();
		set.setJavaScriptEnabled(true);
		set.setBuiltInZoomControls(true);
		
		return linear;
	}
	
	@Override
	public void onPause() {
		super.onPause();
		//현재 프래그먼트에서 키보드 띄운 후 다른 탭을 선택했을 때, 생성되어 있던 키보드를 사라지게 한다. 
		EditText engEdit = (EditText)getActivity().findViewById(R.id.edit_find);
		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(engEdit.getWindowToken(), 0);
		engEdit.setText("");
	}
	
	
	
	
	
	public OnClickListener mClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d(TAG, "onClick");
			LinearLayout lo = (LinearLayout)getActivity().findViewById(R.id.findlayout);
			lo.setBackground(null);
			//입력한 텍스트를 url주소에 추가하여 메소드를 실행한다. 
			EditText editFind = (EditText)getActivity().findViewById(R.id.edit_find);
			//WebView web = (WebView)getActivity().findViewById(R.id.web);
			String word = editFind.getText().toString();
			web.loadUrl("http://m.endic.naver.com/search.nhn?sLn=kr&searchOption=all&query="+word);
			editFind.setText("");
			InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(editFind.getWindowToken(), 0);
		}
	};
	
	
	
	class MyWebClient extends WebViewClient{
		@Override
		//이 메서드를 재정의하여 웹뷰가 url을 받도록 한다. 
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}
	}
}
